package handler

import (
	"admin-system/internal/model"
	"admin-system/internal/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// MenuHandler 菜单处理器
type MenuHandler struct {
	menuService *service.MenuService
}

// NewMenuHandler 创建菜单处理器实例
func NewMenuHandler() *MenuHandler {
	return &MenuHandler{
		menuService: service.NewMenuService(),
	}
}

// List 获取菜单列表
func (h *MenuHandler) List(c *gin.Context) {
	// 获取查询参数
	pageStr := c.DefaultQuery("page", "1")
	pageSizeStr := c.DefaultQuery("page_size", "10")
	keyword := c.Query("keyword")

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil || pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	// 获取菜单列表
	menus, total, err := h.menuService.List(page, pageSize, keyword)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": err.Error(),
		})
		return
	}

	// 转换为响应格式
	var menuResponses []model.MenuResponse
	for _, menu := range menus {
		// 解析Meta JSON
		var meta interface{}
		if menu.Meta != "" {
			// 这里简化处理，实际应该在Service层处理
			meta = menu.Meta
		}

		menuResponses = append(menuResponses, model.MenuResponse{
			ID:        menu.ID,
			ParentID:  menu.ParentID,
			Name:      menu.Name,
			Path:      menu.Path,
			Component: menu.Component,
			Redirect:  menu.Redirect,
			Meta:      meta,
			Sort:      menu.Sort,
			Hidden:    menu.Hidden,
			Status:    menu.Status,
			CreatedAt: menu.CreatedAt,
			UpdatedAt: menu.UpdatedAt,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取菜单列表成功",
		"data": gin.H{
			"list":      menuResponses,
			"total":     total,
			"page":      page,
			"page_size": pageSize,
		},
	})
}

// Tree 获取菜单树
func (h *MenuHandler) Tree(c *gin.Context) {
	menuTree, err := h.menuService.GetTree()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": err.Error(),
		})
		return
	}

	// 调试：打印最终返回的JSON数据
	// jsonData, _ := json.MarshalIndent(menuTree, "", "  ")
	// log.Printf("最终返回给前端的菜单树JSON数据:\n%s", string(jsonData))

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取菜单树成功",
		"data":    menuTree,
	})
}

// Get 获取菜单详情
func (h *MenuHandler) Get(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的菜单ID",
		})
		return
	}

	menu, err := h.menuService.GetByID(uint(id))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": err.Error(),
		})
		return
	}

	// 解析Meta JSON
	var meta interface{}
	if menu.Meta != "" {
		meta = menu.Meta
	}

	response := model.MenuResponse{
		ID:        menu.ID,
		ParentID:  menu.ParentID,
		Name:      menu.Name,
		Path:      menu.Path,
		Component: menu.Component,
		Redirect:  menu.Redirect,
		Meta:      meta,
		Sort:      menu.Sort,
		Hidden:    menu.Hidden,
		Status:    menu.Status,
		CreatedAt: menu.CreatedAt,
		UpdatedAt: menu.UpdatedAt,
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取菜单详情成功",
		"data":    response,
	})
}

// Create 创建菜单
func (h *MenuHandler) Create(c *gin.Context) {
	var req model.MenuCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误: " + err.Error(),
		})
		return
	}

	menu, err := h.menuService.Create(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}

	// 解析Meta JSON
	var meta interface{}
	if menu.Meta != "" {
		meta = menu.Meta
	}

	response := model.MenuResponse{
		ID:        menu.ID,
		ParentID:  menu.ParentID,
		Name:      menu.Name,
		Path:      menu.Path,
		Component: menu.Component,
		Redirect:  menu.Redirect,
		Meta:      meta,
		Sort:      menu.Sort,
		Hidden:    menu.Hidden,
		Status:    menu.Status,
		CreatedAt: menu.CreatedAt,
		UpdatedAt: menu.UpdatedAt,
	}

	c.JSON(http.StatusCreated, gin.H{
		"code":    201,
		"message": "创建菜单成功",
		"data":    response,
	})
}

// Update 更新菜单
func (h *MenuHandler) Update(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的菜单ID",
		})
		return
	}

	var req model.MenuUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误: " + err.Error(),
		})
		return
	}

	menu, err := h.menuService.Update(uint(id), &req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}

	// 解析Meta JSON
	var meta interface{}
	if menu.Meta != "" {
		meta = menu.Meta
	}

	response := model.MenuResponse{
		ID:        menu.ID,
		ParentID:  menu.ParentID,
		Name:      menu.Name,
		Path:      menu.Path,
		Component: menu.Component,
		Redirect:  menu.Redirect,
		Meta:      meta,
		Sort:      menu.Sort,
		Hidden:    menu.Hidden,
		Status:    menu.Status,
		CreatedAt: menu.CreatedAt,
		UpdatedAt: menu.UpdatedAt,
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "更新菜单成功",
		"data":    response,
	})
}

// Delete 删除菜单
func (h *MenuHandler) Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的菜单ID",
		})
		return
	}

	if err := h.menuService.Delete(uint(id)); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "删除菜单成功",
	})
}

// UpdateSort 批量更新菜单排序
func (h *MenuHandler) UpdateSort(c *gin.Context) {
	var req []struct {
		ID   uint `json:"id" binding:"required"`
		Sort int  `json:"sort" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误: " + err.Error(),
		})
		return
	}

	// 转换为Service层需要的类型
	var sortData []struct {
		ID   uint `json:"id"`
		Sort int  `json:"sort"`
	}
	for _, item := range req {
		sortData = append(sortData, struct {
			ID   uint `json:"id"`
			Sort int  `json:"sort"`
		}{
			ID:   item.ID,
			Sort: item.Sort,
		})
	}

	if err := h.menuService.UpdateSort(sortData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "更新菜单排序成功",
	})
}

// GetAll 获取所有菜单（用于角色分配）
func (h *MenuHandler) GetAll(c *gin.Context) {
	menus, err := h.menuService.GetAll()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": err.Error(),
		})
		return
	}

	var menuResponses []model.MenuResponse
	for _, menu := range menus {
		// 解析Meta JSON
		var meta interface{}
		if menu.Meta != "" {
			meta = menu.Meta
		}

		menuResponses = append(menuResponses, model.MenuResponse{
			ID:        menu.ID,
			ParentID:  menu.ParentID,
			Name:      menu.Name,
			Path:      menu.Path,
			Component: menu.Component,
			Redirect:  menu.Redirect,
			Meta:      meta,
			Sort:      menu.Sort,
			Hidden:    menu.Hidden,
			Status:    menu.Status,
			CreatedAt: menu.CreatedAt,
			UpdatedAt: menu.UpdatedAt,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取所有菜单成功",
		"data":    menuResponses,
	})
}

// GetAllTree 获取所有菜单树（用于角色分配）
func (h *MenuHandler) GetAllTree(c *gin.Context) {
	menuTree, err := h.menuService.GetAllTree()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取所有菜单树成功",
		"data":    menuTree,
	})
}
